<template>
  <div class="announcement-detail-container">
    <!-- 未登录用户提示界面 -->
    <el-card v-if="!isAuthenticated" class="login-prompt-card">
      <div class="login-prompt">
        <el-icon class="prompt-icon" size="64"><Lock /></el-icon>
        <h2>需要登录才能查看公告详情</h2>
        <p>此公告内容需要登录后才能查看，请先登录您的账号。</p>
        <div class="prompt-actions">
          <el-button type="primary" size="large" @click="goToLogin">
            立即登录
          </el-button>
          <el-button size="large" @click="goBack">
            返回上一页
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 已登录用户的正常内容 -->
    <el-card v-else-if="announcement" class="announcement-detail-card">
      <template #header>
        <div class="card-header">
          <h1 class="announcement-title">{{ announcement.title }}</h1>
          <div class="announcement-meta">
            <span class="time">发布时间：{{ formatDate(announcement.publishTime || announcement.createTime) }}</span>
          </div>
        </div>
      </template>
      
      <div class="announcement-content">
        <p>{{ announcement.content }}</p>
      </div>
      
      <div class="announcement-files" v-if="files && files.length > 0">
        <h3>附件</h3>
        <el-divider />
        <ul class="file-list">
          <li v-for="file in files" :key="file.id" class="file-item">
            <div class="file-info">
              <el-icon><Document /></el-icon>
              <span class="filename">{{ file.filename }}</span>
              <span class="filesize">({{ formatFileSize(file.size) }})</span>
            </div>
            <div class="file-actions">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleViewFile(file)"
              >
                查看
              </el-button>
              <el-button 
                type="success" 
                size="small" 
                @click="handleDownloadFile(file)"
              >
                下载
              </el-button>
            </div>
          </li>
        </ul>
      </div>
    </el-card>
    
    <el-empty v-else-if="isAuthenticated" description="公告加载中或不存在" />
    
    <div class="back-link">
      <router-link to="/announcements">
        <el-button plain>
          <el-icon><ArrowLeft /></el-icon>
          返回公告列表
        </el-button>
      </router-link>
    </div>
  </div>
</template>

<script>
import { computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document, ArrowLeft, Lock } from '@element-plus/icons-vue'
import config from '../../config'
import axios from 'axios'

export default {
  name: 'AnnouncementDetail',
  components: {
    Document,
    ArrowLeft,
    Lock
  },
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    const store = useStore()
    const router = useRouter()
    
    // 获取登录状态
    const isAuthenticated = computed(() => store.getters.isAuthenticated)
    
    // 公告详情相关数据
    const announcement = computed(() => store.state.announcements.current?.announcement)
    const files = computed(() => store.state.announcements.current?.files || [])
    
    /**
     * 获取公告详情
     * 只有在用户已登录时才调用此函数
     */
    const fetchAnnouncementDetail = async () => {
      if (!isAuthenticated.value) {
        console.log('用户未登录，跳过获取公告详情')
        return
      }
      
      const result = await store.dispatch('fetchAnnouncementDetail', props.id)
      
      if (!result.success) {
        ElMessage.error(result.message || '获取公告详情失败')
      }
    }
    
    /**
     * 跳转到登录页面
     * 登录成功后返回当前页面
     */
    const goToLogin = () => {
      router.push({
        name: 'Login',
        query: { redirect: router.currentRoute.value.fullPath }
      })
    }
    
    /**
     * 返回上一页
     */
    const goBack = () => {
      router.go(-1)
    }
    
    // 初始化
    onMounted(() => {
      // 只有在用户已登录时才获取公告详情
      if (isAuthenticated.value) {
        fetchAnnouncementDetail()
      }
    })
    
    // 日期格式化
    const formatDate = (dateString) => {
      if (!dateString) return '未发布'
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
    
    // 文件大小格式化
    const formatFileSize = (size) => {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB'
      } else {
        return (size / (1024 * 1024)).toFixed(2) + ' MB'
      }
    }
    
    // 查看文件
    const handleViewFile = (file) => {
      const fileUrl = config.getFullResourceUrl(file.url)
      window.open(fileUrl, '_blank')
    }
    
    // 下载文件
    const handleDownloadFile = async (file) => {
      try {
        const downloadUrl = `/api/announcements/files/${file.id}/download`;
        
        // 使用axios发送请求，并正确处理响应类型为blob
        const response = await axios.get(downloadUrl, {
          responseType: 'blob',
          headers: {
            'Authorization': `Bearer ${store.state.token}`
          }
        });
        
        // 从响应头获取文件名
        let filename = file.filename;
        const contentDisposition = response.headers['content-disposition'];
        if (contentDisposition) {
          const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
          if (filenameMatch && filenameMatch[1]) {
            filename = filenameMatch[1].replace(/['"]/g, '');
          }
        }
        
        // 创建URL对象并触发下载
        const blob = new Blob([response.data]);
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
        
        // 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
        
        ElMessage.success('文件下载成功');
      } catch (error) {
        console.error('下载文件失败:', error);
        ElMessage.error('下载文件失败，请重试');
      }
    }
    
    return {
      isAuthenticated,
      announcement,
      files,
      formatDate,
      formatFileSize,
      handleViewFile,
      handleDownloadFile,
      goToLogin,
      goBack
    }
  }
}
</script>

<style scoped>
.announcement-detail-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.announcement-detail-card {
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: 20px;
}

.announcement-title {
  margin: 0 0 10px 0;
  font-size: 1.8rem;
  color: #303133;
}

.announcement-meta {
  display: flex;
  color: #909399;
  font-size: 0.9rem;
}

.time {
  margin-right: 20px;
}

.announcement-content {
  font-size: 1rem;
  line-height: 1.8;
  color: #303133;
  margin: 20px 0;
  white-space: pre-line;
}

.announcement-files {
  margin-top: 30px;
}

.announcement-files h3 {
  font-size: 1.2rem;
  font-weight: 600;
  color: #303133;
}

.file-list {
  list-style: none;
  padding: 0;
  margin: 15px 0;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 8px;
  background-color: #f5f7fa;
  transition: background-color 0.3s;
}

.file-item:hover {
  background-color: #e6f1fc;
}

.file-info {
  display: flex;
  align-items: center;
}

.file-info .el-icon {
  margin-right: 10px;
  color: #409EFF;
  font-size: 18px;
}

.filename {
  font-size: 0.95rem;
  color: #303133;
  margin-right: 5px;
}

.filesize {
  font-size: 0.85rem;
  color: #909399;
}

.file-actions {
  display: flex;
  gap: 10px;
}

.back-link {
  margin-top: 20px;
}

/* 新增：登录提示相关样式 */
.login-prompt-card {
  margin-bottom: 20px;
}

.login-prompt {
  text-align: center;
  padding: 40px 20px;
}

.prompt-icon {
  color: #909399;
  margin-bottom: 20px;
}

.login-prompt h2 {
  margin: 0 0 16px 0;
  font-size: 1.5rem;
  color: #303133;
}

.login-prompt p {
  margin: 0 0 32px 0;
  font-size: 1rem;
  color: #606266;
  line-height: 1.6;
}

.prompt-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}
</style> 